package cn.edu.ujn.park.controller;

import cn.edu.ujn.park.dao.Coupon;
import cn.edu.ujn.park.dao.Payments;
import cn.edu.ujn.park.service.ICouponService;
import cn.edu.ujn.park.service.IPaymentsService;
import cn.edu.ujn.util.Page;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

@Controller
public class PaymentsController {
    @Autowired
    private IPaymentsService paymentsService;

    @Autowired
    private ICouponService couponService;

    @GetMapping("/payments")
    public String list(Model model, HttpServletRequest request,
                       @RequestParam(value = "page", defaultValue = "1") Integer page,
                       @RequestParam(value = "rows", defaultValue = "10") Integer rows, Payments payments) {
        HttpSession session = request.getSession();
        Integer userId = (Integer) session.getAttribute("userId");
        payments.setUserId(userId);
        payments.setStart((page - 1) * rows);
        payments.setRows(rows);
        Page<Payments> page1 = paymentsService.selectAll(payments);
        model.addAttribute("page", page1);
        return "payments";
    }

    @PutMapping("/payments")
    @ResponseBody
    public String update() {
        paymentsService.update();
        return "OK";
    }

    @DeleteMapping("/payments/{id}")
    @ResponseBody
    public String delete(@PathVariable("id") Integer id) {
        int i =  paymentsService.delete(id);
            return "OK";
    }

    @GetMapping("/paying")
    public String payingPage(HttpServletRequest request,
                             @RequestParam("payment_id") String paymentId,
                             @RequestParam("cost") String cost,
                             Model model) {
        HttpSession session = request.getSession();
        Integer userId = (Integer) session.getAttribute("userId");
        List<Coupon> coupons = couponService.selectUserCoupon(userId);
        model.addAttribute("paymentId", paymentId);
        model.addAttribute("cost", cost);
        model.addAttribute("coupons", coupons);
        return "paying";
    }

    @PostMapping("/completePayment")
    @ResponseBody
    public String completePayment(
            @RequestParam("paymentId") Integer paymentId,
            @RequestParam("finalCost") BigDecimal finalCost,
            @RequestParam("couponId") Integer couponId) {
        paymentsService.pay(paymentId,finalCost,couponId);
        couponService.used(couponId);
        return "success";
    }
}
